var gradua = {};

gradua.buildTree = function(spec) {
    console.log(spec);
    var selected = spec.selected;
    var paths = spec.paths;
    var newItemId = spec.newItemId;
    var newItemIdOnAjaxUpdate = spec.newItemIdOnAjaxUpdate;
    var newItemJson = spec.newItemJson;
    var loadingElementId = spec.loadingElementId;
    var containerId = spec.containerId;
    console.log(paths);
    return {
        select: function() {
            $('#'+containerId).removeClass('task-tree');
            $('#'+containerId).addClass('task-tree-selected');
            selected = true;
        },
        deselect: function() {
            $('#'+containerId).removeClass('task-tree-selected');
            $('#'+containerId).addClass('task-tree');
            selected = false;
        },
        isSelected: function() {
            return selected;
        },
        display: function(json) {
           $('#'+containerId).tree(
              {
                lang:{new_node:'New Task'},
                cookies: {prefix:'taskTree'},
                data :
                {
                  type : "json",
                  json: json.tree
                },
                rules: {
                    metadata    : "metadata",
                    use_inline  : true,
                    draggable   : "all"
                },
                callback :
                {
                  onchange: this.onchange,
                  beforemove: this.beforemove,
                  onrename: this.onrename
                },
                ui      : {
                  hover_mode : true,
                  context     : false
                }
              }
            );
            $(document).bind('keypress',this.onkeypress);
            $(document).bind('click',this.selectOrDeselect);
        },
        selectOrDeselect: function(evt) {
            //#### tasks.tree e containerId devem mudar de acordo com o nome da instância da arvore.
            var thisTree = tasks.tree;
            //var containerId = 'content-navigation-container';
            var select = false;
            var parents;
            if($(evt.target).attr('id') == containerId) {
                select = true;
            }
            else {
                parents = $(evt.target).parents();
                for( var a = 0; a < parents.length; a++) {
                    if( $(parents[a]).attr('id') == containerId ) {
                        select = true;
                    }
                }
            }
            if(select) {
                thisTree.select();
            }
            else {
                thisTree.deselect();
            }
        },
        onkeypress: function(evt) {
            //#### tasks.tree deve mudar de acordo com o nome da instância da arvore.
            var thisTree = tasks.tree;
            var selected = thisTree.isSelected();
            if(selected) {
                if (evt.charCode == 32 && $(evt.target).attr('type') != 'text') {//space
                    var itemId = $($.tree_focused().selected[0]).metadata().id;
                    tasks.task.showNodeData({id:itemId});
                    //thisTree.deselect();
                    return false;
                }
                else if (evt.keyCode == 46 && $(evt.target).attr('type') != 'text') { //delete
                    var conf = confirm('Are you sure you want to delete this node and all related information?');
                    if(conf) {
                        thisTree.delete();
                    }
                }
                else if (evt.keyCode == 45) { //insert
                    var selected2 = $($.tree_focused().selected[0]);
                    $.tree_focused().create(clone(newItemJson));
                }
                else if (evt.keyCode == 113) { //F2
                    $.tree_focused().rename();
                }
                //else if (evt.keyCode == 13) { //enter
                else if (evt.keyCode == 34) { //page down
                    var selected2 = $($.tree_focused().selected[0]);
                    $.tree_focused().create(clone(newItemJson), selected2, 'after');
                }
                else if (evt.keyCode == 39 && $(evt.target).attr('type') != 'text') {
                    $.tree_focused().get_right(true);
                    return false;
                }
                else if (evt.keyCode == 37 && $(evt.target).attr('type') != 'text') {
                    $.tree_focused().get_left(true);
                    return false;
                }
                else if (evt.keyCode == 40 && evt.ctrlKey) {
                    var selected2 = $($.tree_focused().selected[0]);
                    var next = selected2.next("li").get(0);
                    if(next) {
                        JsonC.callSfAction(
                            paths.move,
                            {
                                moveId: $(selected2).metadata().id,
                                referenceId: $(next).metadata().id,
                                relativePosition: 'after',
                                refresh: true
                            },
                            loadingElementId
                        );
                    }
                    return false;
                }
                else if (evt.keyCode == 38 && evt.ctrlKey) {
                    var selected2 = $($.tree_focused().selected[0]);
                    var prev = selected2.prev("li").get(0);
                    if(prev) {
                        JsonC.callSfAction(
                            paths.move,
                            {
                                moveId: $(selected2).metadata().id,
                                referenceId: $(prev).metadata().id,
                                relativePosition: 'before',
                                refresh: true
                            },
                            loadingElementId
                        );
                    }
                    return false;
                }
                else if (evt.keyCode == 40) {
                    console.log('uai2');
                    $.tree_focused().get_next(true);
                    return false;
                }
                else if (evt.keyCode == 38) {
                    $.tree_focused().get_prev(true);
                    return false;
                }
            }
        },
        onchange: function(node) {
            // remove novo nó que ainda não foi atualizado ou está atualizando.
            // nó que está atualizando tem o id NOVONOVO-ATUALIZANDO
            if(
              $(node).attr('id') != newItemId
              && ('#'+newItemId).length > 0
            ) {
               $.tree_focused().remove($('#'+newItemId));
            }
            // mostra as informações da categoria contidas como metadata (em atributo do elemento)
            //adminEssays.content.setDs($(node).metadata()).display();
        },
        delete: function(tree) {
           // se ainda não inseriu no banco, não precisa ir ao servidor.
           if($($.tree_focused().selected[0]).attr('id') == newItemId) {
               var selected = $($.tree_focused().selected[0]);
               $.tree_focused().get_prev(true);
               $.tree_focused().remove(selected);
           }
           else {
               var metadata = $($.tree_focused().selected).metadata();
               JsonC.callSfAction(paths.delete, {id:metadata.id}, loadingElementId);
           }
        },
        onrename: function(node,language,tree) {
            newName = $(node).contents().html().toString();
            console.log('onrename');
            // inseriu um novo nó e deu nome, então registra no servidor.
            if ( $(node).attr('id') == newItemId) {
                var relativePosition;
                var refNodeId;
                if($(node).prev().length > 0) {
                    refNodeId = $($(node).prev()).metadata().id;
                    relativePosition = 'after';
                }
                else if($(node).next().length > 0) {
                    refNodeId = $($(node).next()).metadata().id;
                    relativePosition = 'before';
                }
                else {
                    refNodeId = $($(node).parent().parent()).metadata().id,
                    relativePosition = 'inside';
                }
                $(node).attr('id',newItemIdOnAjaxUpdate);
                $(node).attr('metadata','{"id":newItemId}');
                JsonC.callSfAction(
                  paths.insert,
                  {
                      referenceId: refNodeId,
                      relativePosition: relativePosition,
                      name:newName
                  },
                  loadingElementId
                );
            }
            else {
                JsonC.callSfAction(
                  paths.rename,
                  {id:$(node).metadata().id,name:newName},
                  loadingElementId
                );
            }
        },
        beforemove: function(movedNode, referenceNode, relativePosition) {
            if($(movedNode).attr('id') !== newItemId) {
                JsonC.callSfAction(
                    paths.move,
                    {
                        moveId: $(movedNode).metadata().id,
                        referenceId: $(referenceNode).metadata().id,
                        relativePosition: relativePosition
                    },
                    loadingElementId
                );
            }
            return true;
        },
        refresh: function() {
            JsonC.callSfAction(paths.refresh, {}, loadingElementId);
        },
        removeNewNode: function() {
            console.log($('#NOVONOVO-ATUALIZANDO'));
           $('#NOVONOVO-ATUALIZANDO').remove();
        },
        removeById: function(json) {
            //#### tasks.tree deve mudar de acordo com o nome da instância da arvore.
            var thisTree = tasks.tree;
            $.tree_focused().get_prev(true);
            var node = thisTree.findNodeById(json.id);
            if(node.parent().children().length == 1) {
               node.parent().parent().removeClass('open');
               node.parent().parent().addClass('leaf');
               $($(node).parent()[0]).remove()
            }
            else {
              node.remove();
            }
        },
        success: function(json) {
            //dummy function to be called on a sucessfully operation (remome, move, insert, delete...)
        },
        displayItem: function(json) {
          if(json.id = newItemIdOnAjaxUpdate) {
              var node = $('#'+newItemIdOnAjaxUpdate);
              node.removeAttr('id');
          }
          else {
              var node = adminEssays.tree.findNodeById(json.id);
          }
          for(i in json.item.attributes) {
              var attrVal = json.item.attributes[i];
              if(i == 'id') {
                  var newId = attrVal;
              }
              node.attr(i,attrVal);
          }
          node = $('#'+newId);
          $(node).metadata({refresh:true});
        },
        // este método está com um comportamento esquisito, não funcionando quando
        // ainda não foi selecionado nenhum elemento. Parece que tem a ver com o metadata.
        findNodeById: function (id){
            children = $('#'+containerId).children();
            return findOnChildren(children);
            function findOnChildren(children) {
                var l = children.length;
                if(l > 0) {
                    for(var a = 0; a < l; a++) {
                        var item = $(children[a]);
                        var metadata = $(item).metadata();
                        if(metadata.id == id) {
                            return item;
                        }
                        item = findOnChildren(item.children());
                        if(item) return item;
                    }
                }
            }
        }
    }
};


